<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/8
 * Time: 14:06
 */

namespace Home\Controller;


use Common\Logic\ExcelLogic;
use Think\Upload;

/**
 * 通讯录控制器
 * Class ContactController
 * @package Home\Controller
 */
class ContactController extends HomeController
{
    public function index(){
        $this->meta_title = '通讯录管理';
        $fields = 'group_code, group_name';
        $map['state'] = 1;
        $record = M('MailListGroup')->field($fields)->where($map)->select();
        $this->groupList = $record;
        $this->display();
    }

    /**
     * 通讯录导入json接口
     */
    public function import(){
        $flag = false;
        $res = array('success'=>0, 'failed'=>0);
        if(!empty($_FILES['file_import']['name'])){
            $upload = new Upload();
            $upload->exts = array('xls', 'xlsx');
            $upload->savePath = "temp/";
            $upload->saveRule = "time";
            $upload->subName = "";
            if (! $info = $upload->upload ( $_FILES )) {
                $this->error ( $upload->getError () );
            } else { // 上传成功 获叏上传文件信息
                $resurl = $upload->rootPath . $info ['file_import'] ['savepath'] . $info ['file_import'] ['savename'];
                $excelData = ExcelLogic::read($resurl);

                $res = ExcelLogic::importContact($excelData);
//

                if (file_exists ( $resurl )) {
                    unlink ( $resurl );
                }
                $flag = true;
            }

        }
        if ($flag) {
            logOperation('通讯录管理','导入通讯录');
            $this->sucessJson($res);
        } else {
            $this->errorJson( '导入失败' );
        }
    }

    /**
     * 通讯录列表json接口
     * @param $limit
     * @param $offset
     * @param null $search
     * add : 添加一个递归
     *@param $group_code 
     * user: 边个懂
     *time：20170522
     */
    public function mailList($limit, $group_code= 0, $offset, $search = null){ 
        $fields = "ml.mail_list_id, ml.real_name,ml.icon, ml.sex, ml.icon, ml.company, ml.position, ml.phone, ml.office_tel, ml.residence_tel,ml.describe,ml.group_code,ml.add_time, mlg.group_name";
        $map['ml.state'] = 1;
        if (!empty($group_code) && $group_code!= -1) {
            $ids = $this->getgrouplist($group_code);
            !empty($ids) ? $map['ml.group_code'] = array('in',$group_code.','.$ids) : $map['ml.group_code'] = $group_code;
        }
        if (!empty($search)){
            $map['ml.real_name'] = array('like', "%{$search}%");
        }
        if(!empty($this->uids)){
            $map['_string'] = "ml.group_code in(".implode(',', $this->codes).")";
        }
        $record = M('MailList')->alias('ml')->join('mail_list_group mlg on ml.group_code = mlg.group_code', 'left')->field($fields)->where($map)->order('ml.add_time asc')->limit($offset, $limit)->select();
        $total_count = M('MailList')->alias('ml')->where($map)->count();
        empty($total_count) && $total_count = 0;
        $result['rows'] = $record;
        $result['total'] = $total_count;
        $this->ajaxReturn($result);
    }

    /**
    *fun : 递归获取分组方法
    *user: 边个懂
    *time：20170522
    **/
    public function getgrouplist($parent_code,&$result=array()){
         $re = M('MailListGroup')->where("parent_code = ".$parent_code)->select();

         for ($i=0; $i < count($re); $i++) { 
            $result[]= $re[$i]['group_code'];
            $this->getgrouplist($re[$i]['group_code'],$result);
         }
         return implode(',',$result);
    }

    public function delete(){
        $ids = I('selectedIds');
        $where['mail_list_id'] = array('in', $ids);
        $res = M('MailList')->where($where)->setField('state', 0);
        if($res !== false){
            logOperation('通讯录管理','删除通讯录');
            $this->sucessJson();
        }else{
            $this->errorJson('删除失败');
        }
    }

    public function deleteGroup(){
        $ids = I('selectedIds');
        $delOption = I('delOption');
        $where['group_id'] = array('in', $ids);
        $res = M('MailListGroup')->where($where)->setField('state',0);
        if($res !== false){
            $data['group_id'] = 0;
            if($delOption == 1){
                $data['state'] = 0;
            }
            M('MailList')->where($where)->save($data);
            logOperation('通讯录管理','删除组织架构');
            $this->sucessJson();
        }else{
            $this->errorJson('删除失败');
        }
    }


    public function editContact($mail_list_id = null){
        $mailListModel = D('MailList');
        if(IS_POST){
            $this->makePhone('phone');
            $this->makePhone('office_tel');
            $this->makePhone('residence_tel');
            $res = $mailListModel->update();
            if($res){
                logOperation('通讯录管理','编辑通讯录');
                $this->sucessJson($res);
            }else{
                $this->errorJson($mailListModel->getError());
            }
        }else{
            if(empty($mail_list_id)){
                $this->errorJson('参数不正确');
            }else{
                $info = $mailListModel->find($mail_list_id);
                if($info){
                    $this->sucessJson($info);
                }else{
                    $this->errorJson($mailListModel->getError());
                }
            }
        }
    }

    protected function makePhone($field){
        if (isset($_POST[$field])){
            $phone = $_POST[$field];
            if (is_array($phone)){
                $result = '';
                $needSub = false;
                foreach ($phone as $item){
                    if(empty($item)){
                        continue;
                    }
                    $result = $result . $item . ',';
                    $needSub = true;
                }
                if($needSub) {
                    $result = substr($result, 0, -1);
                }
                $_POST[$field] = $result;
            }

        }
    }

    public function allGroupList(){
        $fields = 'group_id, group_name';
        $map['state'] = 1;
        $record = M('MailListGroup')->field($fields)->where($map)->select();
        $this->ajaxReturn();
    }

    /**
     * 群组列表
     */
    public function groupList($limit, $offset, $maxrows){
        $fields = 'group_id, group_name';
        $map['state'] = 1;
        $record = M('MailListGroup')->field($fields)->where($map)->limit($offset, $limit)->select();
        $total_count = M('MailListGroup')->where($map)->count();
        $result['rows'] = $record;
        $result['total'] = $total_count;
        $this->ajaxReturn($result);
    }

    public function editGroup($group_id, $group_name){
        if(empty($group_name)){
            $this->errorJson('群组名不能为空');
        }
        $res = M('MailListGroup')->where("group_id={$group_id}")->setField('group_name', $group_name);
        if($res !== false){
            logOperation('通讯录管理','编辑组织架构');
            $this->sucessJson();
        }else{
            $this->errorJson('群组名修改失败');
        }
    }

    public function addGroup($group_name){
        if(empty($group_name)){
            $this->errorJson('群组名不能为空');
        }
        $data['group_name'] = $group_name;
        $model = M('MailListGroup');
        if($model->create($data)){
            $id = $model->add();
            if($id > 0){
                logOperation('通讯录管理','新增组织架构');
                $this->sucessJson();
            }
        }
        $this->errorJson('新增失败');
    }


}